package com.woniu.service.impl;

import com.woniu.Asserts;
import com.woniu.OrderFeignClient;
import com.woniu.Result;
import com.woniu.dto.OrderDto;
import com.woniu.dto.OrderPayDto;
import com.woniu.pojo.AliPay;
import com.woniu.pojo.vo.CodeVo;
import com.woniu.vo.OrderQueryVo;
import com.woniu.mqwork.OrderMqProduct;
import com.woniu.pojo.Care;
import com.woniu.mapper.CareMapper;
import com.woniu.pojo.vo.OrderVo;
import com.woniu.pojo.vo.PaymentVo;
import com.woniu.service.ICareService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zbk
 * @since 2022-11-16
 */
@Service
@Slf4j
public class CareServiceImpl extends ServiceImpl<CareMapper, Care> implements ICareService {

    @Autowired(required = false)
    private CareMapper careMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private OrderMqProduct orderMqProduct;

    private static long n = 1;

    @Override
    public List<Care> queryAllCare(Integer shopId) {
        //判断redis有无
        String key = "care:list";
        List list = redisTemplate.opsForList().range(key, 0, -1);

        if(list == null || list.size() <= 0){
            // 查数据库
            log.info("查数据库");
            List<Care> careList = careMapper.selectAllCare(shopId);

            // 存入redis
            redisTemplate.opsForList().leftPushAll(key, careList);
            return careList;
        }else{
            // 查redis
            log.info("查redis");
            return list;
        }

    }

    @Override
    public OrderVo submitOrder(Integer productId, String userId, Integer shopId) {

        Care care = careMapper.selectById(productId);

        // 创建订单
        OrderDto orderDto = new OrderDto();
        orderDto.setUserId(userId);
        orderDto.setProductId(productId);
        orderDto.setPrice(care.getPrice().add(care.getTimeMoney()));
        orderDto.setProductName(care.getName());
        orderDto.setShopId(shopId);

        String orderSn = orderFeignClient.createOrder(orderDto).getData();
        return OrderVo.builder().userId(userId).orderSn(orderSn).build();
    }

    @Override
    public PaymentVo confirmOrder(OrderPayDto orderPayDto, String userId) {

        String orderSn = orderPayDto.getOrderSn();

        // 远程调用查询订单信息
        OrderQueryVo orderQueryVo = orderFeignClient.findOrderByOrderSn(orderSn).getData();

        // 判断订单状态
        if(orderQueryVo.getStatus() == 4){
            Asserts.failed("订单已失效");
        }
        if(orderQueryVo.getStatus() == 3){
            Asserts.failed("订单已关闭");
        }

        // 修改库存
        careMapper.updateStorage(orderPayDto.getProductId());

        // 用mq进行计时
        orderMqProduct.sendMsg(orderPayDto);

        PaymentVo paymentVo = PaymentVo.builder().orderSn(orderSn).userId(userId).totalAmount(orderQueryVo.getTotalAmount()).build();
        return paymentVo;
    }

    @Override
    public Result<String> payOrder(OrderPayDto orderPayDto, String userId, HttpServletResponse httpResponse) {
        // 支付宝
        OrderQueryVo orderQueryVo = orderFeignClient.findOrderByOrderSn(orderPayDto.getOrderSn()).getData();

        AliPay aliPay = new AliPay();
        aliPay.setTraceNo(orderPayDto.getOrderSn());
        aliPay.setSubject(String.valueOf(orderPayDto.getProductId()));
        aliPay.setTotalAmount(orderQueryVo.getTotalAmount());

        // 修改订单状态
        String result = orderFeignClient.updateOrderStatus(orderPayDto).getData();
        if(result.equals("success")){
            // 生成验证码
            long code = createCode(n);
            String key = "code:" + userId;
            CodeVo codeVo = new CodeVo();
            codeVo.setCode(String.valueOf(code));
            codeVo.setOrderSn(orderPayDto.getOrderSn());
            // 存入redis
            redisTemplate.opsForSet().add(key, codeVo);
            return Result.ok(String.valueOf(code));
        }
        return Result.fail("支付失败");
    }

    @Override
    public Result<String> verifyCode(String code, String userId) {
        String key = "code:" + userId;
        Set<CodeVo> members = redisTemplate.opsForSet().members(key);
        for (CodeVo member : members) {
            if(code.equals(member.getCode())){
                orderFeignClient.updateStatus(member.getOrderSn());
                return Result.ok(member.toString());
            }
        }
        return Result.fail("验证失败");
    }

//    /**
//     * 根据父id查询
//     * @param parentId
//     * @return
//     */
//    public List<CareVo> queryByParentId(Integer parentId){
//        List<CareVo> careVoList = careMapper.queryByParentId(parentId);
//        return careVoList;
//    }

    /**
     * 生成编码
     * @param l
     * @return
     */
    public long createCode(long l) {
        String str = new SimpleDateFormat("yyyyMM").format(new Date());
        long m = Long.parseLong((str)) * 100000;
        long ret = m + l;
        n = l + 1;
        return ret;
    }
}
